<template>
  <!--新增/编辑计划-->
  <vx-popup :title="dialogTitle" width="1000px" @close="cancelSubmit" :active.sync="dialogVisible" @confirmPopup="handleSubmit" @cancelPopup="cancelSubmit" clearable>
    <el-form :model="ruleForm" :rules="rules" ref="ruleForm" class="demo-ruleForm">
      <div class="insp-task-addPage-basic">
        <el-row justify="space-between" :gutter="20">
          <!-- <el-col :span="12">
            <el-form-item label="计划名称 :" prop="name" label-width="95px">
              <el-input v-model="ruleForm.name" placeholder="请输入计划名称" size="small" style="width:100%" clearable>
              </el-input>
            </el-form-item>
          </el-col> -->

          <el-col :span="12">
            <el-form-item label="巡检类型 :" prop="inspType" label-width="95px">
              <el-select :disabled="fagle" v-model="ruleForm.inspType" placeholder="请选择巡检类型" size="small" style="width: 100%" clearable>
                <el-option label="日常巡检" :value="0"></el-option>
                <el-option label="定期巡检" :value="1"></el-option>
                <!-- <el-option label="特殊巡检" :value="2"></el-option> -->
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <!-- <el-form-item label="执行区间 :" prop="execTime" label-width="95px"> -->
            <el-form-item label="执行区间 :" label-width="95px">
              <!-- <el-date-picker
                :disabled="fagle"
              
                :default-time="['12:00:00']"
                style="width: 100%"
                v-model="ruleForm.execTime"
                type="daterange"
                size="small"
                range-separator="——"
                start-placeholder="开始时间"
                end-placeholder="结束时间"
                clearable
              >
              </el-date-picker> -->

              <el-date-picker
                :disabled="fagle"
                value-format="yyyy-MM-dd HH:mm:ss"
                :default-time="['00:00:00']"
                style="width: 100%"
                @change="changetime"
                v-model="ruleForm.execTime"
                type="daterange"
                size="small"
                range-separator="——"
                start-placeholder="开始时间"
                end-placeholder="结束时间"
                clearable
              >
              </el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row justify="space-between" :gutter="20">
          <el-col :span="12">
            <el-form-item label="巡检周期 :" prop="type" label-width="95px">
              <el-select :disabled="fagle" v-model="ruleForm.type" @change="select(ruleForm.type)" placeholder="请选择巡检周期" size="small" style="width: 100%" clearable>
                <el-option label="月" :value="0"></el-option>
                <el-option label="日" :value="1"></el-option>
                <el-option label="周" :value="3"></el-option>
              </el-select>
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="巡检频次 :" label-width="95px">
              每<el-input :disabled="fagle" v-model.number="ruleForm.cycle" size="small" style="width: 20%; margin: 0 10px" clearable> </el-input> {{ type }}巡检<span style="color: red">1</span>次
            </el-form-item>
          </el-col>
        </el-row>

        <el-row justify="space-between" :gutter="20">
          <!-- <el-col :span="12">
            <el-form-item label="有效区间 :" prop="validTime" label-width="95px">
              <el-date-picker
                value-format="yyyy-MM-dd HH:mm:ss"
                format="yyyy-MM-dd HH:mm:ss"
                :default-time="['12:00:00']"
                style="width: 100%"
                v-model="ruleForm.validTime"
                type="datetimerange"
                size="small"
                range-separator="——"
                start-placeholder="开始时间"
                end-placeholder="结束时间"
                clearable
              >
              </el-date-picker>
            </el-form-item>
          </el-col> -->
        </el-row>
      </div>

      <div class="insp-task-addPage-line" v-for="(item, index) in ruleForm.inspBridges" :key="index" style="height: 118px">
        <div class="insp-task-addPage-left">
          <div class="insp-task-addPage-item">
            <el-form-item label="巡检桥梁 :" :rules="{ required: true, message: '请选择巡检桥梁', trigger: 'change' }" label-width="95px">
              <el-select
                filterable
                v-model="ruleForm.bridgeList"
                :disabled="fagle"
                multiple
                placeholder="请选择巡检桥梁"
                size="small"
                style="width: 695px"
                @change="(event) => handleBridgeChange(event, index)"
                clearable
                value-key="id"
              >
                <!-- <el-option v-for="temp in bridgeOptions" :key="temp.id" :label="temp.name" :value="temp"> </el-option> 没改之前代码 -->
                <el-option v-for="temp in bridgeOptions" :key="temp.id" :label="temp.name" :value="`${temp.id};${temp.name}`"> </el-option>
              </el-select>
            </el-form-item>
          </div>
          <!-- <div class="insp-task-addPage-item">
            <el-form-item label="巡检项 :" :prop="'inspBridges[' + index + '].name'" :rules="{ required: false, message: '请选择巡检项', trigger: 'change' }" label-width="95px">
              <el-cascader
                v-model="item.name"
                :options="deasePosOptions[index] || []"
                @change="(event) => handleChangeDeasePos(event, index)"
                :key="isResouceShow"
                :props="{ label: 'name', value: 'value', children: 'children' }"
                size="small"
                style="width: 300px"
                placeholder="请选择巡检项"
                clearable
              >
              </el-cascader>
            </el-form-item>
          </div> -->
          <div class="insp-task-addPage-item">
            <el-form-item label="巡检规范 :" :rules="{ required: true, message: '请选择巡检规范', trigger: 'change' }" label-width="95px">
              <el-select :disabled="fagle" v-model="ruleForm.inspStandard" placeholder="请选择巡检规范" size="small" style="width: 300px" clearable>
                <el-option label="城市桥梁" :value="0"></el-option>
                <el-option label="道路桥梁" :value="1"></el-option>
              </el-select>
            </el-form-item>
          </div>
          <div class="insp-task-addPage-item">
            <!-- <el-form-item label="巡检员 :" :prop="'inspBridges[' + index + '].itemUserList'" :rules="{ required: false, message: '请选择巡检员', trigger: 'change' }" label-width="95px"> -->
            <el-form-item label="巡检员 :" :rules="{ required: true, message: '请选择巡检员', trigger: 'change' }" label-width="95px">
              <el-select
                filterable
                :disabled="fagle"
                v-model="ruleForm.itemUserList"
                placeholder="请选择巡检员"
                @change="(event) => changeUserList(event)"
                size="small"
                multiple
                collapse-tags
                style="width: 300px"
                clearable
              >
                <el-option v-for="item in personOptions" :key="item.realId" :label="item.name" :value="`${item.realId};${item.name}`"> </el-option>
                <div style="text-align: center">
                  <el-pagination
                    @current-change="handlePageChange_sel"
                    :current-page.sync="currentPage_sel"
                    :hide-on-single-page="true"
                    :page-size="pagesize_sel"
                    layout="prev, pager, next"
                    :total="recordsTotal_sel"
                  >
                  </el-pagination>
                </div>
              </el-select>
            </el-form-item>
          </div>
        </div>
        <!-- <div class="insp-task-addPage-right">
          <div class="insp-task-addPage-item">
            <el-form-item lable-width="0">
              <el-button circle size="mini" type="danger" style="margin-left: 10px" icon="el-icon-minus" @click="handleDeleteItem(item, index)"> </el-button>
            </el-form-item>
          </div>
        </div> -->
      </div>

      <!-- <div class="insp-task-addPage-btn">
        <el-button size="mini" type="primary" class="insp-task-addBtn" icon="el-icon-plus" @click="handleAddLine"> </el-button>
      </div> -->
    </el-form>
  </vx-popup>
</template>

<script>
var numbersRules = (value, callback) => {
  var reg = /^[1-9]\d*$/
  if (value != null && value != '') {
    if (!reg.test(value)) {
      callback(new Error('请输入整数,值范围在0-1000000000之间!'))
    } else {
      callback()
    }
  } else {
    callback()
  }
}

export default {
  props: {},
  data() {
    return {
      fagle: false,
      isResouceShow: 0,
      dialogTitle: '',
      editId: '',
      dialogVisible: false,
      bridgeOptions: [],
      monthOptions: [],
      type: '',
      dayOptions: [],
      personOptions: [],
      deasePosOptions: {},
      ext1Data: [],
      bridgeArrS: [],
      bridgeNameData: [],
      ruleForm: {
        // name: '',
        inspType: '',
        type: '',
        month: '',
        day: '',
        cron: '',
        inspStandard: '',
        bridgeList: [],
        itemUserList: [],
        inspBridges: [
          {
            bridge: '',
            // name: [],

            itemUserList: [],
          },
        ],
      },

      rules: {
        name: [
          {
            required: true,
            message: '请输入计划名称',
            trigger: 'blur',
          },
        ],
        inspType: [
          {
            required: true,
            message: '请选择巡检类型',
            trigger: 'change',
          },
        ],
        type: [
          {
            required: true,
            message: '请选择巡检周期',
            trigger: 'change',
          },
        ],
        cycle: [
          {
            required: true,
            message: '请填写频次',
            trigger: 'blur',
          },
          { required: true, trigger: 'blur', validator: numbersRules },
        ],
        execTime: [
          {
            required: true,
            message: '请选择执行区间',
            trigger: 'change',
          },
        ],
        validTime: [
          {
            required: true,
            message: '请选择有效区间',
            trigger: 'change',
          },
        ],
      },
      currentPage_sel: 1,
      pagesize_sel: 10,
      recordsTotal_sel: 0,
    }
  },
  computed: {
    return: {},
  },
  created() {
    this.queryBridgeList()
    this.queryPersonList(1)
    this.dayOptions = this.createNumberOptions(31, '日')
    this.monthOptions = this.createNumberOptions(12, '月')
  },

  mounted() {},
  methods: {
    select(num) {
      console.log(num, 'num')
      if (num == 0) {
        this.type = '月'
      } else if (num == 1) {
        this.type = '日'
      } else {
        this.type = '周'
      }
    },
    add() {
      ;(this.fagle = false), (this.dialogVisible = true)
      this.dialogTitle = '新增计划'
      this.editId = null
      this.emptyForm()
    },
    edit(val) {
      this.$refs['ruleForm'].resetFields()
      ;(this.fagle = true), (this.dialogVisible = true)
      this.dialogTitle = '计划详情'
      this.editId = val
      this.queryPlanById(val)
    },
    emptyForm() {
      this.$refs['ruleForm'].resetFields()
      const emptyObj = {
        name: '',
        inspType: '',
        type: '',
        month: '',
        day: '',
        cron: '',

        inspBridges: [
          {
            bridge: '',
            name: [],
            inspStandard: '',
            itemUserList: [],
          },
        ],
      }
      this.ruleForm = emptyObj
    },
    queryBridgeList() {
      this.$api.bridge.AllTheBridges().then((response) => {
        if (response.data.success) {
          console.log(response.data, 'bridgeOptions')
          this.bridgeOptions = response.data.data[0]
        }
      })
    },
    changetime(e) {
      console.log(e, 'time')
    },
    queryPlanById(val) {
      this.fagle = true
      this.$api.insp.queryPlanById(val).then((response) => {
        const _data = response.data.data
        console.log(response.data.data, 'jihua')
        this.ruleForm.bridgeList.push(_data.name)
        this.ruleForm.itemUserList.push(_data.itemUserList)
        this.ruleForm.type = _data.type
        this.ruleForm.cycle = _data.cycle
        this.ruleForm.inspType = _data.inspType
        this.ruleForm.inspStandard = _data.inspStandard
        this.ruleForm.itemUserList = []
        _data.itemUserList.map((item) => {
          console.log(item.userName, '_datauserName')
          this.ruleForm.itemUserList.push(item.userName)
        })
        // console.log(this.ruleForm.itemUserList, '_data.itemUserList')
        this.ruleForm.execTime = [_data.beginExec, _data.endExec]
        if (_data.type == 0) {
          this.type = '月'
        } else if (_data.type == 1) {
          this.type = '日'
        } else {
          this.type = '周'
        }

        // 逻辑变了下面旧代码注释
        // let _inspBridges = _data.itemList.map((item, index) => {
        //   // let _itemUserList = item.itemUserList.map((userItem) => `${userItem.userId};${userItem.userName}`)
        //   let _ext1 = JSON.parse(item.ext1)
        //   this.handleBridgeChange(_ext1, index)
        //   return {
        //     name: [`${item.constructionId};${item.constructionName}`, `${item.partsId};${item.partsName}`],
        //     inspStandard: item.inspStandard,
        //     bridge: _ext1,
        //     // itemUserList: _itemUserList,
        //   }
        // })

        // let _ruleForm = {
        //   name: _data.name,
        //   type: _data.type,
        //   cycle: _data.cycle,
        //   validTime: [_data.validStartTime, _data.validEndTime],
        //   execTime: [_data.beginExec, _data.endExec],
        //   inspType: _data.inspType,
        //   inspBridges: _inspBridges,
        // }
        // this.ruleForm = _ruleForm
      })
    },
    // handleAddLine() {
    //   this.ruleForm.inspBridges.push({
    //     bridge: '',
    //     name: [],
    //     inspStandard: '',
    //     itemUserList: [],
    //   })
    // },
    // handleDeleteItem(item, index) {
    //   this.ruleForm.inspBridges.splice(index, 1)
    // },
    handleSubmit() {
      console.log('111')
      this.$refs.ruleForm.validate(async (valid) => {
        if (!valid) {
          return false
        }
        // 巡检人id name传值处理
        let arr = []
        this.ruleForm.itemUserList.map((item) => {
          arr.push({
            orgId: null,
            orgName: null,
            userId: item.split(';')[0],
            userName: item.split(';')[1],
          })
        })
        // 桥梁传值id bridgeName传值处理
        this.bridgeArrS = []
        this.ext1Data.map((item) => {
          this.bridgeArrS.push({
            bridgeId: item.id,
            bridgeName: item.name,
            ext1: JSON.stringify({
              id: item.id,
              name: item.name,
              lng: item.lng,
              lat: item.lat,
              bridgeTypeId: item.bridgeTypeId,
              bridgeTypeName: item.bridgeTypeName,
              province: item.provinceName,
              city: item.municipalityName,
              area: item.regionName,
              standardName: item.standardName,
            }),
            inspPlanCfgPos: {
              ownId: item.id,
              ownName: item.name,
              lon: item.lng,
              lat: item.lat,
            },
          })
        })

        console.log(this.ruleForm.bridgeList)

        let _userInfo = JSON.parse(localStorage.getItem('userInfo'))
        // let _itemList = this.ruleForm.inspBridges.map((item) => {
        //   let _itemUserList = item.itemUserList.map((temp) => ({
        //     userId: temp.split(';')[0],
        //     userName: temp.split(';')[1],
        //   }))
        //   let _ext1 = {
        //     // ...item.bridge,
        //     id: item.bridge['id'] || '',
        //     name: item.bridge['name'] || '',
        //     lng: item.bridge['lng'] || '',
        //     lat: item.bridge['lat'] || '',
        //     bridgeTypeId: item.bridge['bridgeTypeId'] || '',
        //     bridgeTypeName: item.bridge['bridgeTypeName'] || '',
        //     province: item.bridge['provinceName'] || '',
        //     city: item.bridge['municipalityName'] || '',
        //     area: item.bridge['regionName'] || '',
        //     standardName: item.bridge['standardName'] || '',
        //   }

        //   return {
        //     name: item.name.length > 0 ? `${item.name[0].split(';')[1]}/${item.name[1].split(';')[1]}` : '',
        //     constructionId: item.name.length > 0 ? item.name[0].split(';')[0] : '',
        //     constructionName: item.name.length > 0 ? item.name[0].split(';')[1] : '',
        //     partsId: item.name.length > 0 ? item.name[1].split(';')[0] : '',
        //     partsName: item.name.length > 0 ? item.name[1].split(';')[1] : '',
        //     ownId: item.bridge['id'] || '',
        //     ownName: item.bridge['name'] || '',
        //     inspPlanCfgPos: {
        //       ownId: item.bridge['id'] || '',
        //       ownName: item.bridge['name'] || '',
        //       lon: item.bridge['lng'] || '',
        //       lat: item.bridge['lat'] || '',
        //     },
        //     inspStandard: parseInt(item.inspStandard),
        //     // itemUserList: _itemUserList,
        //
        //   }
        // })
        let _endExec = this.ruleForm.execTime[1].substring(0, 10)
        console.log(_endExec)
        let _params = {
          createUserId: _userInfo['userid'] || '',
          createUserName: _userInfo['realname'] || '',
          // name: this.ruleForm.name,
          inspType: this.ruleForm.inspType,
          type: this.ruleForm.type,
          cycle: parseInt(this.ruleForm.cycle),
          beginExec: this.ruleForm.execTime[0],
          endExec: `${_endExec} 23:59:59`,
          // validStartTime: this.ruleForm.validTime[0],
          // validEndTime: this.ruleForm.validTime[1],
          inspStandard: this.ruleForm.inspStandard,
          bridgeList: this.bridgeArrS,
          itemUserList: arr,
        }

        if (this.editId) {
          _params.id = this.editId
        }

        if (this.editId) {
          this.dialogVisible = false
          this.$emit('closeAddInspPlan')
          // this.$api.insp.updatePlan(_params).then((response) => {
          //   if (response.data.success) {
          //     this.$vs.notify({
          //       text: '修改成功',
          //       color: 'success',
          //       icon: 'success',
          //     })
          // this.dialogVisible = false
          // this.$emit('closeAddInspPlan')

          //   }
          // })
        } else {
          this.$api.insp.addPlan(_params).then((response) => {
            if (response.data.success) {
              this.$vs.notify({
                text: '新增成功',
                color: 'success',
                icon: 'success',
              })
              this.bridgeArrS = []
              this.ext1Data = []
              this.dialogVisible = false
              this.$emit('closeAddInspPlan')
            }
          })
        }
      })
    },
    cancelSubmit() {
      this.dialogVisible = false
      this.ruleForm.bridgeList = []
      this.ruleForm.itemUserList = []
      this.ruleForm.type = ''
      this.ruleForm.cycle = ''
      this.ruleForm.inspType = ''
      this.ruleForm.inspStandard = ''
    },
    queryPersonList(pageIndex) {
      if (pageIndex && pageIndex === 1) {
        this.currentPage_sel = 1
      }
      const _params = {
        pageSize: this.pagesize_sel,
        pageNum: this.currentPage_sel,
        type: '0',
      }
      this.$api.personManager.getPersonList(_params).then((response) => {
        if (response.data.success) {
          this.personOptions = response.data.data
          console.log(this.personOptions, 'this.personOptions')
          this.recordsTotal_sel = response.data.recordsTotal
        }
      })
    },
    handlePageChange_sel(currentPage) {
      this.currentPage_sel = currentPage
      this.queryPersonList()
    },
    changeUserList(e) {
      // console.log(e)
      // var arr = []
      // e.map((item) => {
      //   arr.push({
      //     orgId: null,
      //     orgName: null,
      //     userId: item.split(';')[0],
      //     userName: item.split(';')[1],
      //   })
      // })
      // // 组件方法有重复数据去重
      // var obj = {}
      // for (var i = 0; i < arr.length; i++) {
      //   if (!obj[arr[i].key]) {
      //     this.itemUserList.push(arr[i])
      //     obj[arr[i].key] = true
      //   }
      // }
    },
    handleBridgeChange(event, index) {
      this.ext1Data = []
      console.log(this.ext1Data, 'this.ext1Data.push')
      let bridgeId = ''
      let bridgeArr = event.map((item) => {
        return item.slice(0, 18)
      })

      console.log(bridgeArr, 'bridgeArr')
      this.bridgeOptions.map((item) => {
        bridgeArr.map((temp) => {
          if (item.id == temp) {
            this.ext1Data.push(item)
          }
        })
      })

      const _params = {
        bridgeTypeId: event['bridgeTypeId'] || '',
        pId: '-1',
        bridgeId: event['id'] || '',
      }
      this.queryConstructionModelTreeById(_params, index)
    },
    handleChangeDeasePos(event, index) {},
    deepDeasePosOptions(data) {
      let _arr = []
      let _obj = {}
      data.map((item) => {
        const _tmp = {
          ...item,
        }
        if (_tmp.children && _tmp.children.length > 0) {
          _tmp.children = this.deepDeasePosOptions(_tmp.children)
        }
        _obj = {
          id: _tmp.id,
          name: _tmp.name,
          value: `${_tmp.id};${_tmp.name}`,
        }
        if (_tmp.children && _tmp.children.length > 0) {
          _obj.children = _tmp.children
        }
        _arr.push(_obj)
      })
      return _arr
    },
    queryConstructionModelTreeById(_params, index) {
      this.$api.bridge.queryConstructionModelTreeById(_params).then((response) => {
        if (response.data.success) {
          ++this.isResouceShow
          this.deasePosOptions[index] = this.deepDeasePosOptions(response.data.data.children)
        }
      })
    },
    createNumberOptions(length, unit) {
      let _options = []
      for (let i = 0; i < length; i++) {
        _options.push({
          label: `${i + 1}${unit}`,
          value: i + 1,
        })
      }
      return _options
    },
  },
}
</script>
<style lang="scss" scoped>
@import '@/assets/scss/baseColor.scss';
@import '../insp.scss';
</style>
